package site.xuxingcan.autodownload;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;

import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * Created by Administrator on 2016/9/28.
 */
public class UpdateUtil {
    public static File downloadApk(String urlStr) {
        try {
            File file = new File(Environment.getExternalStorageDirectory(), "update.apk");
            if (file.exists()) {
                file.delete();
            }
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(30 * 1000);
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream inputStream = conn.getInputStream();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            inputStream.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String shouldUpdate(Context context) {
        try {
            AVQuery<AVObject> query = new AVQuery<>("Update");
            List<AVObject> list = query.find();
            if (list.size() != 0) {
                int VersionCode = list.get(0).getInt("VersionCode");
                if (VersionCode > getVersion(context)) {
                    return list.get(0).getString("URL");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static int getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
}
